﻿// ------------------------------------------------------------------------------
// <copyright file="FlipView.cs" company="skumaronline.com">
//    Copyright (C) 2012 Suresh Kumar T.  All rights reserved.
// </copyright>
// ------------------------------------------------------------------------------

namespace StoreAppLib.Controls
{
    using System.Collections.Generic;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;

    /// <summary>
    /// Custom flip view to fix flickering when setting selected item
    /// </summary>
    public class FlipViewX : Windows.UI.Xaml.Controls.FlipView
    {
        /// <summary>
        /// Variable to hold the flip view items.
        /// </summary>
        private Dictionary<object, FlipViewItem> flipViewItems;

        /// <summary>
        /// Variable to hold the last selected item.
        /// </summary>
        private object lastSelectedItem;       

        /// <summary>
        /// Initializes a new instance of the <see cref="FlipView"/> class"
        /// </summary>
        public FlipViewX() : base()
        {
            this.flipViewItems = new Dictionary<object, FlipViewItem>();

            this.SelectionChanged += OnFlipViewSelectionChanged;
            this.LayoutUpdated += OnFlipViewLayoutUpdated;
        }

        /// <summary>
        /// Reassign selected item on layout is updated. This is to ensure that selection changed event fires for the selected item.
        /// </summary>
        /// <param name="sender">The sender</param>
        /// <param name="e">The argument</param>
        private void OnFlipViewLayoutUpdated(object sender, object e)
        {
            if (this.lastSelectedItem != this.SelectedItem)
            {
                this.lastSelectedItem = this.SelectedItem;
                this.SelectedItem = null;
                this.SelectedItem = this.lastSelectedItem;
            }
        }

        /// <summary>
        /// Fires when selection changes. Make the current item visible.
        /// </summary>
        /// <param name="sender">The sender</param>
        /// <param name="e">The argument</param>
        private void OnFlipViewSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            foreach (object item in this.flipViewItems.Keys)
            {
                this.flipViewItems[item].Visibility = (item == this.SelectedItem) ? Visibility.Visible : Visibility.Collapsed;
            }
        }        
    }
}
